package hander

import (
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
	"week4/retailers/api-client/basic/api/request"
	__ "week4/retailers/api-client/proto"
)

func List(c *gin.Context) {
	var req request.List
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数验证失败",
			"data": nil,
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:8805", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	client := __.NewUserClient(conn)

	list, _ := client.List(c, &__.ListRequest{
		Page: int64(req.Page),
		Size: int64(req.Size),
	})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": list,
	})

}

func Info(c *gin.Context) {
	var req request.Info
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数验证失败",
			"data": nil,
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:8805", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	client := __.NewUserClient(conn)

	list, _ := client.Info(c, &__.InfoRequest{
		Id: int64(req.Id),
	})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "详情展示成功",
		"data": list,
	})
}

func Add(c *gin.Context) {
	var req request.Add
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数验证失败",
			"data": nil,
		})
		return
	}
	conn, err := grpc.NewClient("127.0.0.1:8805", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	client := __.NewUserClient(conn)

	list, _ := client.Add(c, &__.AddRequest{
		Name:      req.Name,
		Price:     req.Price,
		Num:       req.Num,
		Address:   req.Address,
		SendPhone: req.SendPhone,
		Recipient: req.Recipient,
	})

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": list,
	})
}
